import { computed, ref, watch } from 'vue';

import { useUserStore } from '@vben/stores';

import { message } from 'ant-design-vue';
import { defineStore, storeToRefs } from 'pinia';

import { getCaptchaApi, shopBindPhoneApi } from '#/api';
import { auto1688stor, useAuthStore } from '#/store';

export const bindPhoneStore = defineStore('bindPhone', () => {
  const userStore = useUserStore();
  const authStore = useAuthStore();

  const auto1688storTres = auto1688stor();

  const nowData = computed(() => auto1688storTres.auto1688.nowSelectDyShop);
  const { userInfo } = storeToRefs(userStore);
  const bindBoxState = ref(false);
  const getCodeOutTime = ref(0);
  const getSendCodeState = ref(false);

  const upDataLogin = ref(false);

  const binfFromData: any = ref({
    phone: userInfo.value?.phonenumber,
    code: '',
    // 密码
    // password: '',
    // // 确认密码
    // confirmPassword: '',
  });
  function $reset() {
    getCodeOutTime.value = 0;
    getSendCodeState.value = false;
    upDataLogin.value = false;
    binfFromData.value = {
      phone: '',
      code: '',
    };
  }
  async function sendCode() {
    if (!nowData.value) {
      message.error('请先选择店铺');
      return;
    }
    getSendCodeState.value = true;
    const res = await getCaptchaApi({
      phoneNumber: binfFromData.value.phone,
      sendType: 5,
    }).finally(() => {
      getSendCodeState.value = false;
    });
    getSendCodeState.value = false;
    if (res) {
      message.success('验证码已发送');
    }
    getCodeOutTime.value = 60;
    const timer = setInterval(() => {
      getCodeOutTime.value--;
      if (getCodeOutTime.value === 0) {
        clearInterval(timer);
      }
    }, 1000);
  }
  function bindPhone() {
    // console.log('bindPhone', nowData);
    if (!binfFromData.value.phone || !binfFromData.value.code) {
      message.error('请输入手机号和验证码');
      return;
    }
    upDataLogin.value = true;
    shopBindPhoneApi({
      phoneNumber: binfFromData.value.phone,
      phoneCode: binfFromData.value.code,
      shopName: nowData.value.shopName,
      shopId: nowData.value.shopId,
    }).then((res) => {
      if (res) {
        upDataLogin.value = false;
        $reset();
        message.success('绑定成功');
        bindBoxState.value = false;
        authStore.fetchUserInfo();
        // userStore.getUserInfo();
      }
    });
  }

  watch(userInfo, () => {
    binfFromData.value.phone = userInfo.value?.phonenumber;
  });

  return {
    $reset,
    bindBoxState,
    binfFromData,
    sendCode,
    getCodeOutTime,
    getSendCodeState,
    bindPhone,
    upDataLogin,
  };
});
